package com.zgkxzx.myfix;

import android.content.Context;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.jar.Attributes;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.jar.Manifest;
import java.util.zip.ZipEntry;

/**
 * 创建者 zgkxzx
 * 日期   1/30/18
 * 描述   Patch文件解析
 */
public class Patch {
    private final static String TAG = Patch.class.getSimpleName();

    private Context context;
    private File mFile;

    private static final String PATCH_CLASSES = "Patch-Classes";
    private static final String ENTRY_NAME = "META-INF/PATCH.MF";
    private Map<String, List<String>> mClassMap;


    public Patch(String src, Context context) {

        this.context = context;
        mFile = new File(src);
        init();

    }

    private void init() {
        JarFile jarFile = null;
        InputStream inputStream = null;


        mClassMap = new HashMap<>();
        try {
            jarFile = new JarFile(mFile);
            JarEntry jarEntry = jarFile.getJarEntry(ENTRY_NAME);
            inputStream = jarFile.getInputStream(jarEntry);

            Manifest manifest = new Manifest(inputStream);
            Attributes mainAttributes = manifest.getMainAttributes();

            Attributes.Name name;

            List<String> list;

            for (Iterator<Object> iterator = mainAttributes.keySet().iterator(); iterator.hasNext(); ) {
                name = (Attributes.Name) iterator.next();
                if (name != null) {
                    String attributeName = name.toString();
                    if (attributeName.endsWith("Classes")) {
                        list = Arrays.asList(mainAttributes.getValue(attributeName).split(","));
                        if (attributeName.equalsIgnoreCase(PATCH_CLASSES)) {
                            mClassMap.put(attributeName, list);
                        } else {
                            mClassMap.put(attributeName.trim().substring(0, attributeName.length() - 8), list);
                        }
                    }
                }
            }


        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                jarFile.close();
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


    }

    public Set<String> getPatchNames() {
        return mClassMap.keySet();
    }

    public List<String> getClasses(String name) {
        return mClassMap.get(name);
    }
}
